package com.csii.user.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csii.autopoi.poi.excel.ExcelImportUtil;
import com.csii.autopoi.poi.excel.entity.ExportParams;
import com.csii.autopoi.poi.excel.entity.ImportParams;
import com.csii.autopoi.web.def.NormalExcelConstants;
import com.csii.autopoi.web.view.EntityExcelView;
import com.csii.core.annotation.PermissionData;
import com.csii.core.api.Result;
import com.csii.core.constant.CommonConstant;
import com.csii.core.constant.PublishAndSubscribeConstant;
import com.csii.core.system.query.QueryGenerator;
import com.csii.core.system.vo.ComboModel;
import com.csii.core.system.vo.LoginUser;
import com.csii.core.system.vo.SysUserCacheInfo;
import com.csii.core.util.ImportExcelUtil;
import com.csii.core.util.RedisUtil;
import com.csii.core.util.TenantContext;
import com.csii.core.util.oConvertUtils;
import com.csii.user.entity.*;
import com.csii.user.model.DepartIdModel;
import com.csii.user.model.SysUserSysDepartModel;
import com.csii.user.model.UpdateUserModel;
import com.csii.user.service.*;
import com.csii.user.vo.SysDepartUsersVO;
import com.csii.user.vo.SysUserRoleVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author ian
 * @since 2018-12-20
 */
@Slf4j
@RestController
@RequestMapping("/sys/user")
@Api(tags = "用户接口")
public class SysUserController {
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysUserDepartService sysUserDepartService;
    @Autowired
    private ISysDepartRoleUserService departRoleUserService;
    @Autowired
    private ISysDepartRoleService departRoleService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ISysRoleService iSysRoleService;

    @Value("${stdio.path.upload}")
    private String upLoadPath;
    @Value("${ldap.enable:true}")
    private Boolean ldapEnable;

    @Value("${csii.user.register.default.tenantIds:0}")
    private String userRegisterDefaultTenantIds;
    @Value("${csii.user.register.default.roles:1387351073907281921}")
    private String userRegisterDefaultRoles;

    @ApiOperation(value = "获取缓存用户信息")
    @RequestMapping(value = {"/getCacheUser"}, method = RequestMethod.GET)
    public Result<SysUserCacheInfo> getCacheUser(String username) {
        return Result.ok(sysUserService.getCacheUser(username));
    }

    /**
     * 获取用户列表数据
     *
     * @param user
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @PermissionData(pageComponent = "system/UserList")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(value = "数据列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "搜索关键字")})
    public Result<IPage<SysUser>> queryPageList(SysUser user, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req, String keyword) {
        Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
        queryWrapper.and(StrUtil.isNotBlank(keyword), i -> i.like("username", keyword).or().like("realname", keyword));
        queryWrapper.and(w -> {
            w.likeLeft("rel_tenant_ids", "," + TenantContext.getTenant())
                    .or().likeRight("rel_tenant_ids", TenantContext.getTenant() + ",").or().eq("rel_tenant_ids", TenantContext.getTenant());
        });
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);

        //批量查询用户的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询用户的所属部门名字
        List<String> userIds = pageList.getRecords().stream().map(SysUser::getId).collect(Collectors.toList());
        if (userIds != null && userIds.size() > 0) {
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            pageList.getRecords().forEach(item -> {
                item.setOrgCodeTxt(useDepNames.get(item.getId()));
            });
        }
        result.setSuccess(true);
        result.setResult(pageList);
        log.info(pageList.toString());
        return result;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<SysUser> add(@RequestBody JSONObject jsonObject) {
        Result<SysUser> result = new Result<SysUser>();
        String selectedRoles = jsonObject.getString("selectedroles");
        String selectedDeparts = jsonObject.getString("selecteddeparts");
        try {
            SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
            if (!isSuperAdminRole()) {
                user.setRelTenantIds(TenantContext.getTenant());
            }
            String password = user.getPassword();
            user.setCreateTime(new Date());//设置创建时间
            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
            user.setStatus(1);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            sysUserService.addUserWithRole(user, selectedRoles);
            sysUserService.addUserWithDepart(user, selectedDeparts);

            if (ldapEnable) {
                //保存到ldap用户中
                sysUserService.saveGroupUser(user, password, selectedRoles);
            }

            Result.ok("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    private boolean isSuperAdminRole() {
        Set<String> role = AuthorityUtils.authorityListToSet(SecurityContextHolder.getContext().getAuthentication().getAuthorities());
        return "0".equals(TenantContext.getTenant()) && role.contains("ROLE_admin");
    }

    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public Result<SysUser> edit(@RequestBody JSONObject jsonObject) {
        Result<SysUser> result = new Result<SysUser>();
        try {
            SysUser sysUser = sysUserService.getById(jsonObject.getString("id"));
            sysBaseAPI.addLog("编辑用户，id： " + jsonObject.getString("id"), CommonConstant.LOG_TYPE_2, 2);
            if (sysUser == null) {
                result.error500("未找到对应实体");
            } else {
                SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
                if (!isSuperAdminRole()) {
                    user.setRelTenantIds(null);
                }
                user.setUpdateTime(new Date());
                String roles = jsonObject.getString("selectedroles");
                String roleGroups = jsonObject.getString("selectedroleGroups");
                String departs = jsonObject.getString("selecteddeparts");
                sysUserService.editUserWithRole(user, roles, roleGroups);
                sysUserService.editUserWithDepart(user, departs);
                sysUserService.updateNullPhoneEmail();
                if (ldapEnable) {
                    // 修改ldap中的用户信息
                    sysUserService.updateGroupUser(user, roles);
                }
                sysUserService.valiUserCahce(sysUser.getUsername());
                Result.ok("修改成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 删除用户
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        sysBaseAPI.addLog("删除用户，id： " + id, CommonConstant.LOG_TYPE_2, 3);
        SysUser sysUser = sysUserService.getById(id);
        this.sysUserService.deleteUser(id);
        //发布消息
        List<SysUser> sysUserList = new ArrayList<>();
        sysUserList.add(sysUser);

        return Result.ok("删除用户成功");
    }

    /**
     * 批量删除用户
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        sysBaseAPI.addLog("批量删除用户， ids： " + ids, CommonConstant.LOG_TYPE_2, 3);
        List<SysUser> sysUserList = sysUserService.listByIds(Arrays.asList(ids.split(",")));
        this.sysUserService.deleteBatchUsers(ids);
        //发布消息
        //.publish(PublishAndSubscribeConstant.USER_INFO_DELETE_SYNC, sysUserList);
        return Result.ok("批量删除用户成功");
    }

    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result<SysUser> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<SysUser> result = new Result<SysUser>();
        SysUser sysUser = sysUserService.getById(id);
        if (sysUser == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(sysUser);
            result.setSuccess(true);
        }
        return result;
    }

    @RequestMapping(value = "/queryUserRole", method = RequestMethod.GET)
    public Result<List<String>> queryUserRole(@RequestParam(name = "userid", required = true) String userid) {
        Result<List<String>> result = new Result<>();
        List<String> list = new ArrayList<String>();
        List<SysUserRole> userRole = sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, userid).isNotNull(SysUserRole::getRoleId));
        if (userRole == null || userRole.size() <= 0) {
            result.error500("未找到用户相关角色信息");
        } else {
            for (SysUserRole sysUserRole : userRole) {
                list.add(sysUserRole.getRoleId());
            }
            result.setSuccess(true);
            result.setResult(list);
        }
        return result;
    }

    @RequestMapping(value = "/queryUserRoleGroup", method = RequestMethod.GET)
    public Result<List<String>> queryUserRoleGroup(@RequestParam(name = "userid", required = true) String userid) {
        Result<List<String>> result = new Result<>();
        List<String> list = new ArrayList<String>();
        List<SysUserRole> userRole = sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, userid).isNotNull(SysUserRole::getRoleGroupId));
        if (userRole == null || userRole.size() <= 0) {
            result.error500("未找到用户相关角色组信息");
        } else {
            for (SysUserRole sysUserRole : userRole) {
                list.add(sysUserRole.getRoleGroupId());
            }
            result.setSuccess(true);
            result.setResult(list);
        }
        return result;
    }

    /**
     * 校验用户账号是否唯一<br>
     * 可以校验其他 需要检验什么就传什么。。。
     *
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "/checkOnlyUser", method = RequestMethod.GET)
    public Result<Boolean> checkOnlyUser(SysUser sysUser) {
        Result<Boolean> result = new Result<>();
        //如果此参数为false则程序发生异常
        result.setResult(true);
        try {
            //通过传入信息查询新的用户信息
            SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>(sysUser));
            if (user != null) {
                result.setSuccess(false);
                result.setMessage("用户账号已存在");
                return result;
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * 修改密码
     */
    @RequestMapping(value = "/changePassword", method = RequestMethod.PUT)
    public Result<?> changePassword(@RequestBody SysUser sysUser) {
        SysUser u = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, sysUser.getUsername()));
        if (u == null) {
            return Result.error("用户不存在！");
        }
        sysUser.setId(u.getId());
        return sysUserService.changePassword(sysUser);
    }

    /**
     * 修改当前登录人密码
     */
    @RequestMapping(value = "/changeCurrentUserPassword", method = RequestMethod.PUT)
    public Result<?> changeCurrentUserPassword(@RequestBody SysUser sysUser) {
        sysUser.setUsername(((LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
        return changePassword(sysUser);
    }

    /**
     * 查询指定用户和部门关联的数据
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/userDepartList", method = RequestMethod.GET)
    public Result<List<DepartIdModel>> getUserDepartsList(@RequestParam(name = "userId", required = true) String userId) {
        Result<List<DepartIdModel>> result = new Result<>();
        try {
            List<DepartIdModel> depIdModelList = this.sysUserDepartService.queryDepartIdsOfUser(userId);
            if (depIdModelList != null && depIdModelList.size() > 0) {
                result.setSuccess(true);
                result.setMessage("查找成功");
                result.setResult(depIdModelList);
            } else {
                result.setSuccess(false);
                result.setMessage("查找失败");
            }
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("查找过程中出现了异常: " + e.getMessage());
            return result;
        }

    }

    @RequestMapping(value = "/listUserDepartList", method = RequestMethod.GET)
    public Result<List<SysDepart>> listUserDepartList(@RequestParam(name = "userId", required = true) String userId) {
        Result<List<SysDepart>> result = new Result<>();
        try {
            List<SysDepart> depModelList = sysDepartService.queryUserDeparts(userId);
            result.setSuccess(true);
            result.setMessage("查找成功");
            result.setResult(depModelList);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("查找过程中出现了异常: " + e.getMessage());
            return result;
        }

    }

    /**
     * 生成在添加用户情况下没有主键的问题,返回给前端,根据该id绑定部门数据
     *
     * @return
     */
    @RequestMapping(value = "/generateUserId", method = RequestMethod.GET)
    public Result<String> generateUserId() {
        Result<String> result = new Result<>();
        System.out.println("我执行了,生成用户ID==============================");
        String userId = UUID.randomUUID().toString().replace("-", "");
        result.setSuccess(true);
        result.setResult(userId);
        return result;
    }

    /**
     * 根据部门id查询用户信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryUserByDepId", method = RequestMethod.GET)
    @ApiOperation(value = "根据部门id查询用户列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "部门ID"),
            @ApiImplicitParam(name = "realname", value = "搜索关键字")})
    public Result<List<SysUser>> queryUserByDepId(@RequestParam(name = "id", required = true) String id,
                                                  @RequestParam(name = "realname", required = false) String realname) {
        Result<List<SysUser>> result = new Result<>();
        //List<SysUser> userList = sysUserDepartService.queryUserByDepId(id);
        SysDepart sysDepart = sysDepartService.getById(id);
        List<SysUser> userList = sysUserDepartService.queryUserByDepCode(sysDepart.getOrgCode(), realname);

        //批量查询用户的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询用户的所属部门名字
        List<String> userIds = userList.stream().map(SysUser::getId).collect(Collectors.toList());
        if (userIds != null && userIds.size() > 0) {
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            userList.forEach(item -> {
                //TODO 临时借用这个字段用于页面展示
                item.setOrgCode(useDepNames.get(item.getId()));
            });
        }

        try {
            result.setSuccess(true);
            result.setResult(userList);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            return result;
        }
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sysUser
     */
    @GetMapping(value = "/exportXls")
    public ModelAndView exportXls(SysUser sysUser, HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(sysUser, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new EntityExcelView());
        //update-begin--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据--------------------
        String selections = request.getParameter("selections");
        if (!oConvertUtils.isEmpty(selections)) {
            queryWrapper.in("id", selections.split(","));
        }
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<SysUser> pageList = sysUserService.list(queryWrapper);

        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "用户列表");
        mv.addObject(NormalExcelConstants.CLASS, SysUser.class);
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        ExportParams exportParams = new ExportParams("用户列表数据", "导出人:" + user.getRealname(), "导出信息");
        exportParams.setImageBasePath(upLoadPath);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        // 错误信息
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
			InputStream isr = null;
            try {
				isr = file.getInputStream();
                List<SysUser> listSysUsers = ExcelImportUtil.importExcel(isr, SysUser.class, params);
                for (int i = 0; i < listSysUsers.size(); i++) {
                    SysUser sysUserExcel = listSysUsers.get(i);
                    if (StringUtils.isBlank(sysUserExcel.getPassword())) {
                        // 密码默认为 “123456”
                        sysUserExcel.setPassword("123456");
                    }
                    sysUserExcel.setPassword(new BCryptPasswordEncoder().encode(sysUserExcel.getPassword()));
                    try {
                        sysUserService.save(sysUserExcel);
                        successLines++;
                    } catch (Exception e) {
                        errorLines++;
                        String message = e.getMessage();
                        int lineNumber = i + 1;
                        // 通过索引名判断出错信息
                        if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_USERNAME)) {
                            errorMessage.add("第 " + lineNumber + " 行：用户名已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_WORK_NO)) {
                            errorMessage.add("第 " + lineNumber + " 行：工号已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_PHONE)) {
                            errorMessage.add("第 " + lineNumber + " 行：手机号已经存在，忽略导入。");
                        } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_EMAIL)) {
                            errorMessage.add("第 " + lineNumber + " 行：电子邮件已经存在，忽略导入。");
                        } else {
                            errorMessage.add("第 " + lineNumber + " 行：未知错误，忽略导入");
                            log.error(e.getMessage(), e);
                        }
                    }
                    // 批量将部门和用户信息建立关联关系
                    String departIds = sysUserExcel.getDepartIds();
                    if (StringUtils.isNotBlank(departIds)) {
                        String userId = sysUserExcel.getId();
                        String[] departIdArray = departIds.split(",");
                        List<SysUserDepart> userDepartList = new ArrayList<>(departIdArray.length);
                        for (String departId : departIdArray) {
                            userDepartList.add(new SysUserDepart(userId, departId));
                        }
                        sysUserDepartService.saveBatch(userDepartList);
                    }

                }
            } catch (Exception e) {
                errorMessage.add("发生异常：" + e.getMessage());
                log.error(e.getMessage(), e);
            } finally {
                if (isr != null) {
                    try {
                        isr.close();
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        }
        return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);
    }

    /**
     * @param userIds
     * @return
     * @功能：根据id 批量查询
     */
    @RequestMapping(value = "/queryByIds", method = RequestMethod.GET)
    public Result<Collection<SysUser>> queryByIds(@RequestParam String userIds) {
        Result<Collection<SysUser>> result = new Result<>();
        String[] userId = userIds.split(",");
        Collection<String> idList = Arrays.asList(userId);
        Collection<SysUser> userRole = sysUserService.listByIds(idList);
        result.setSuccess(true);
        result.setResult(userRole);
        return result;
    }

    /**
     * 首页用户重置密码
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.PUT)
    public Result<?> changPassword(@RequestBody JSONObject json) {
        String username = json.getString("username");
        String oldpassword = json.getString("oldpassword");
        String password = json.getString("password");
        String confirmpassword = json.getString("confirmpassword");
        SysUser user = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
        if (user == null) {
            return Result.error("用户不存在！");
        }
        return sysUserService.resetPassword(username, oldpassword, password, confirmpassword);
    }

    @RequestMapping(value = "/userRoleList", method = RequestMethod.GET)
    public Result<IPage<SysUser>> userRoleList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        String roleId = req.getParameter("roleId");
        String username = req.getParameter("username");
        IPage<SysUser> pageList = sysUserService.getUserByRoleId(page, roleId, username);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @RequestMapping(value = "/userGroupList", method = RequestMethod.GET)
    public Result<IPage<SysUser>> userGroupList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, @RequestParam String groupId, @RequestParam(required = false) String username) {
        Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        IPage<SysUser> pageList = sysUserService.getUserByGroupId(page, groupId, username);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 给指定角色添加用户
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/addSysUserRole", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result<String> addSysUserRole(@RequestBody SysUserRoleVO sysUserRoleVO) {
        Result<String> result = new Result<String>();
        try {
            // 根据userIds查询所有的用户
            List<SysUser> userList = sysUserService.getUserListAndRole(sysUserRoleVO.getUserIdList());
            String sysRoleId = sysUserRoleVO.getRoleId();
            // 查询角色名称
            SysRole role = iSysRoleService.getById(sysRoleId);
            for (String sysUserId : sysUserRoleVO.getUserIdList()) {
                SysUserRole sysUserRole = new SysUserRole(sysUserId, sysRoleId);
                QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
                queryWrapper.eq("role_id", sysRoleId).eq("user_id", sysUserId);
                SysUserRole one = sysUserRoleService.getOne(queryWrapper);
                if (one == null) {
                    sysUserRoleService.save(sysUserRole);
                    if (ldapEnable) {
                        // 增加一个角色
                        sysUserService.addOrDelRoleForGroupUser(sysUserId, sysRoleId, true);
                    }
                }

            }
            result.setMessage("添加成功!");
            result.setSuccess(true);

            // 发布消息
            if (CollUtil.isNotEmpty(userList)) {
                userList.forEach(user -> {
                    if (CollUtil.isNotEmpty(user.getRoleList())) {
                        user.getRoleList().add(role);
                    } else {
                        List<SysRole> roleList = new ArrayList<>();
                        roleList.add(role);
                        user.setRoleList(roleList);
                    }
                });
            }
            //publishService.publish(PublishAndSubscribeConstant.USER_INFO_UPDATE_SYNC, userList);

            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("出错了: " + e.getMessage());
            return result;
        }
    }

    /**
     * 删除指定角色的用户关系
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/deleteUserRole", method = RequestMethod.DELETE)
    @Transactional(rollbackFor = Exception.class)
    public Result<SysUserRole> deleteUserRole(@RequestParam(name = "roleId") String roleId,
                                              @RequestParam(name = "userId", required = true) String userId) {
        Result<SysUserRole> result = new Result<SysUserRole>();
        try {
            // 查询用户的详细信息和角色
            List<SysUser> userList = sysUserService.getUserListAndRole(Arrays.asList(userId));
            SysRole role = iSysRoleService.getById(roleId);
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
            queryWrapper.eq("role_id", roleId).eq("user_id", userId);
            sysUserRoleService.remove(queryWrapper);
            Result.ok("删除成功!");
            if (ldapEnable) {
                // 删除一个角色
                sysUserService.addOrDelRoleForGroupUser(userId, roleId, false);
            }

            // 发布消息
            userList.forEach(user -> {
                if (CollUtil.isNotEmpty(user.getRoleList())) {
                    List<SysRole> collect = user.getRoleList().stream().filter(f -> !role.getRoleName().equals(f.getRoleName())).collect(Collectors.toList());
                    user.setRoleList(collect);
                }
            });
            //publishService.publish(PublishAndSubscribeConstant.USER_INFO_UPDATE_SYNC, userList);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 批量删除指定角色的用户关系
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/deleteUserRoleBatch", method = RequestMethod.DELETE)
    public Result<SysUserRole> deleteUserRoleBatch(@RequestParam(name = "roleId") String roleId,
                                                   @RequestParam(name = "userIds", required = true) String userIds) {
        Result<SysUserRole> result = new Result<SysUserRole>();
        try {
            List<String> ids = Arrays.asList(userIds.split(","));
            // 查询用户的详细信息和角色
            List<SysUser> userList = sysUserService.getUserListAndRole(ids);
            SysRole role = iSysRoleService.getById(roleId);
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
            queryWrapper.eq("role_id", roleId).in("user_id", ids);
            sysUserRoleService.remove(queryWrapper);
            Result.ok("删除成功!");
            if (ldapEnable) {
                // 删除ldap用户的角色
                ids.forEach(id -> sysUserService.addOrDelRoleForGroupUser(id, roleId, false));
            }

            // 发布消息
            userList.forEach(user -> {
                if (CollUtil.isNotEmpty(user.getRoleList())) {
                    List<SysRole> collect = user.getRoleList().stream().filter(f -> !role.getRoleName().equals(f.getRoleName())).collect(Collectors.toList());
                    user.setRoleList(collect);
                }
            });
            //publishService.publish(PublishAndSubscribeConstant.USER_INFO_UPDATE_SYNC, userList);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }


    /**
     * 给指定角色添加用户组
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/addSysUserGroup", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result<String> addSysUserGroup(@RequestBody SysUserRoleVO sysUserRoleVO) {
        Result<String> result = new Result<String>();
        try {
            String sysRoleId = sysUserRoleVO.getRoleId();
            for (String sysUserId : sysUserRoleVO.getUserIdList()) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleGroupId(sysRoleId);
                sysUserRole.setUserId(sysUserId);
                QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
                queryWrapper.eq("role_group_id", sysRoleId).eq("user_id", sysUserId);
                SysUserRole one = sysUserRoleService.getOne(queryWrapper);
                if (one == null) {
                    sysUserRoleService.save(sysUserRole);
                    if (ldapEnable) {
                        // 增加一个角色
                        sysUserService.addOrDelRoleForGroupUser(sysUserId, sysRoleId, true);
                    }
                }

            }
            result.setMessage("添加成功!");
            result.setSuccess(true);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("出错了: " + e.getMessage());
            return result;
        }
    }

    /**
     * 删除指定角色组的用户关系
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/deleteUserGroup", method = RequestMethod.DELETE)
    @Transactional(rollbackFor = Exception.class)
    public Result<SysUserRole> deleteUserGroup(@RequestParam(name = "groupId") String groupId,
                                               @RequestParam(name = "userId", required = true) String userId) {
        Result<SysUserRole> result = new Result<SysUserRole>();
        try {
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
            queryWrapper.eq("role_group_id", groupId).eq("user_id", userId);
            sysUserRoleService.remove(queryWrapper);
            Result.ok("删除成功!");
            if (ldapEnable) {
                // 删除一个角色
                sysUserService.addOrDelRoleForGroupUser(userId, groupId, false);
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 批量删除指定角色组的用户关系
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/deleteUserGroupBatch", method = RequestMethod.DELETE)
    public Result<SysUserRole> deleteUserGroupBatch(@RequestParam(name = "groupId") String groupId,
                                                    @RequestParam(name = "userIds", required = true) String userIds) {
        Result<SysUserRole> result = new Result<SysUserRole>();
        try {
            List<String> ids = Arrays.asList(userIds.split(","));
            // 查询用户的详细信息和角色
            List<SysUser> userList = sysUserService.getUserListAndRole(ids);
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
            queryWrapper.eq("role_group_id", groupId).in("user_id", ids);
            sysUserRoleService.remove(queryWrapper);
            Result.ok("删除成功!");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 部门用户列表
     */
    @RequestMapping(value = "/departUserList", method = RequestMethod.GET)
    public Result<IPage<SysUser>> departUserList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        String depId = req.getParameter("depId");
        String username = req.getParameter("username");
        //根据部门ID查询,当前和下级所有的部门IDS
        List<String> subDepids = new ArrayList<>();
        //部门id为空时，查询我的部门下所有用户
        if (oConvertUtils.isEmpty(depId)) {
            LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            int userIdentity = user.getUserIdentity() != null ? user.getUserIdentity() : CommonConstant.USER_IDENTITY_1;
            if (oConvertUtils.isNotEmpty(userIdentity) && userIdentity == CommonConstant.USER_IDENTITY_2) {
                subDepids = sysDepartService.getMySubDepIdsByDepId(user.getDepartIds());
            }
        } else {
            subDepids = sysDepartService.getSubDepIdsByDepId(depId);
        }
        if (subDepids != null && subDepids.size() > 0) {
            IPage<SysUser> pageList = sysUserService.getUserByDepIds(page, subDepids, username);
            //批量查询用户的所属部门
            //step.1 先拿到全部的 useids
            //step.2 通过 useids，一次性查询用户的所属部门名字
            List<String> userIds = pageList.getRecords().stream().map(SysUser::getId).collect(Collectors.toList());
            if (userIds != null && userIds.size() > 0) {
                Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
                pageList.getRecords().forEach(item -> {
                    //批量查询用户的所属部门
                    item.setOrgCode(useDepNames.get(item.getId()));
                });
            }
            result.setSuccess(true);
            result.setResult(pageList);
        } else {
            result.setSuccess(true);
            result.setResult(null);
        }
        return result;
    }


    /**
     * 根据 orgCode 查询用户，包括子部门下的用户
     * 若某个用户包含多个部门，则会显示多条记录，可自行处理成单条记录
     */
    @GetMapping("/queryByOrgCode")
    public Result<?> queryByDepartId(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "orgCode") String orgCode,
            SysUser userParams
    ) {
        IPage<SysUserSysDepartModel> pageList = sysUserService.queryUserByOrgCode(orgCode, userParams, new Page(pageNo, pageSize));
        return Result.ok(pageList);
    }

    /**
     * 根据 orgCode 查询用户，包括子部门下的用户
     * 针对通讯录模块做的接口，将多个部门的用户合并成一条记录，并转成对前端友好的格式
     */
    @GetMapping("/queryByOrgCodeForAddressList")
    public Result<?> queryByOrgCodeForAddressList(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "orgCode", required = false) String orgCode,
            SysUser userParams
    ) {
        IPage page = new Page(pageNo, pageSize);
        IPage<SysUserSysDepartModel> pageList = sysUserService.queryUserByOrgCode(orgCode, userParams, page);
        return Result.ok(pageList);
    }

    /**
     * 给指定部门添加对应的用户
     */
    @RequestMapping(value = "/editSysDepartWithUser", method = RequestMethod.POST)
    public Result<String> editSysDepartWithUser(@RequestBody SysDepartUsersVO sysDepartUsersVO) {
        Result<String> result = new Result<String>();
        try {
            String sysDepId = sysDepartUsersVO.getDepId();
            for (String sysUserId : sysDepartUsersVO.getUserIdList()) {
                SysUserDepart sysUserDepart = new SysUserDepart(null, sysUserId, sysDepId);
                QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
                queryWrapper.eq("dep_id", sysDepId).eq("user_id", sysUserId);
                SysUserDepart one = sysUserDepartService.getOne(queryWrapper);
                if (one == null) {
                    sysUserDepartService.save(sysUserDepart);
                }
            }
            result.setMessage("添加成功!");
            result.setSuccess(true);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("出错了: " + e.getMessage());
            return result;
        }
    }

    /**
     * 删除指定机构的用户关系
     */
    @RequestMapping(value = "/deleteUserInDepart", method = RequestMethod.DELETE)
    public Result<SysUserDepart> deleteUserInDepart(@RequestParam(name = "depId") String depId,
                                                    @RequestParam(name = "userId", required = true) String userId
    ) {
        Result<SysUserDepart> result = new Result<SysUserDepart>();
        try {
            QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
            queryWrapper.eq("dep_id", depId).eq("user_id", userId);
            boolean b = sysUserDepartService.remove(queryWrapper);
            if (b) {
                List<SysDepartRole> sysDepartRoleList = departRoleService.list(new QueryWrapper<SysDepartRole>().eq("depart_id", depId));
                List<String> roleIds = sysDepartRoleList.stream().map(SysDepartRole::getId).collect(Collectors.toList());
                if (roleIds != null && roleIds.size() > 0) {
                    QueryWrapper<SysDepartRoleUser> query = new QueryWrapper<>();
                    query.eq("user_id", userId).in("drole_id", roleIds);
                    departRoleUserService.remove(query);
                }
                Result.ok("删除成功!");
            } else {
                result.error500("当前选中部门与用户无关联关系!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 批量删除指定机构的用户关系
     */
    @RequestMapping(value = "/deleteUserInDepartBatch", method = RequestMethod.DELETE)
    public Result<SysUserDepart> deleteUserInDepartBatch(
            @RequestParam(name = "depId") String depId,
            @RequestParam(name = "userIds", required = true) String userIds) {
        Result<SysUserDepart> result = new Result<SysUserDepart>();
        try {
            QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
            queryWrapper.eq("dep_id", depId).in("user_id", Arrays.asList(userIds.split(",")));
            boolean b = sysUserDepartService.remove(queryWrapper);
            if (b) {
                departRoleUserService.removeDeptRoleUser(Arrays.asList(userIds.split(",")), depId);
            }
            Result.ok("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 查询当前用户的所有部门/当前部门编码
     *
     * @return
     */
    @RequestMapping(value = "/getCurrentUserDeparts", method = RequestMethod.GET)
    public Result<Map<String, Object>> getCurrentUserDeparts() {
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        try {
            LoginUser sysUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            List<SysDepart> list = this.sysDepartService.queryUserDeparts(sysUser.getId());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("list", list);
            map.put("orgCode", sysUserService.getUserByName(sysUser.getUsername()).getOrgCode());
            result.setSuccess(true);
            result.setResult(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("查询失败！");
        }
        return result;
    }


    /**
     * 用户注册接口
     *
     * @return
     */
    @PostMapping("/register")
    public Result<JSONObject> userRegister(@RequestBody JSONObject jsonObject) {
        Result<JSONObject> result = new Result<JSONObject>();
        String phone = jsonObject.getString("mobile");
        String smscode = jsonObject.getString("code");
        Object code = redisUtil.get(phone);
        String username = jsonObject.getString("name");
        String realname = jsonObject.getString("name");

        SysUser sysUser2 = sysUserService.getUserByPhone(phone);
        if (sysUser2 != null) {
            result.setMessage("该手机号已注册");
            result.setSuccess(false);
            result.setCode(401);
            return result;
        }

        if (!smscode.equals(code)) {
            result.setMessage("手机验证码错误");
            result.setSuccess(false);
            result.setCode(401);
            return result;
        }

        //未设置用户名，则用手机号作为用户名
        if (oConvertUtils.isEmpty(username)) {
            username = phone;
        }
        //未设置密码，则随机生成一个密码
        String password = jsonObject.getString("password");
        if (oConvertUtils.isEmpty(password)) {
            password = RandomUtil.randomString(8);
        }
        String email = jsonObject.getString("email");
        SysUser sysUser1 = sysUserService.getUserByName(username);
        if (sysUser1 != null) {
            result.setMessage("用户名已注册");
            result.setCode(401);
            result.setSuccess(false);
            return result;
        }


        if (oConvertUtils.isNotEmpty(email)) {
            SysUser sysUser3 = sysUserService.getUserByEmail(email);
            if (sysUser3 != null) {
                result.setMessage("邮箱已被注册");
                result.setSuccess(false);
                result.setCode(401);
                return result;
            }
        }


        try {
            SysUser user = new SysUser();
            user.setCreateTime(new Date());// 设置创建时间
            user.setUsername(username);
            user.setRealname(realname);
            user.setPassword(new BCryptPasswordEncoder().encode(password));
            user.setEmail(email);
            user.setPhone(phone);
            user.setStatus(CommonConstant.USER_UNFREEZE);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            user.setActivitiSync(CommonConstant.ACT_SYNC_0);
            //设置默认租户ID
            TenantContext.setTenant(userRegisterDefaultTenantIds);
            sysUserService.addUserWithRole(user, null, userRegisterDefaultRoles);
            //还原租户ID
            TenantContext.setTenant(null);
            redisUtil.del(phone);
            return Result.ok("注册成功");
        } catch (Exception e) {
            result.error500("注册失败");
        }
        return result;
    }

    /**
     * 根据用户名或手机号查询用户信息
     *
     * @param
     * @return
     */
    @GetMapping("/querySysUser")
    public Result<Map<String, Object>> querySysUser(SysUser sysUser) {
        String phone = sysUser.getPhone();
        String username = sysUser.getUsername();
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        if (oConvertUtils.isNotEmpty(phone)) {
            SysUser user = sysUserService.getUserByPhone(phone);
            if (user != null) {
                map.put("username", user.getUsername());
                map.put("phone", user.getPhone());
                result.setSuccess(true);
                result.setResult(map);
                return result;
            }
        }
        if (oConvertUtils.isNotEmpty(username)) {
            SysUser user = sysUserService.getUserByName(username);
            if (user != null) {
                map.put("username", user.getUsername());
                map.put("phone", user.getPhone());
                result.setSuccess(true);
                result.setResult(map);
                return result;
            }
        }
        result.setSuccess(false);
        result.setMessage("验证失败");
        return result;
    }

    /**
     * 用户手机号验证
     */
    @PostMapping("/phoneVerification")
    public Result<Map<String, String>> phoneVerification(@RequestBody JSONObject jsonObject) {
        Result<Map<String, String>> result = new Result<Map<String, String>>();
        String phone = jsonObject.getString("phone");
        String smscode = jsonObject.getString("smscode");
        Object code = redisUtil.get(phone);
        if (!smscode.equals(code)) {
            result.setMessage("手机验证码错误");
            result.setSuccess(false);
            return result;
        }
        //设置有效时间
        redisUtil.set(phone, smscode, 600);
        //新增查询用户名
        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
        query.eq(SysUser::getPhone, phone);
        SysUser user = sysUserService.getOne(query);
        Map<String, String> map = new HashMap<>();
        map.put("smscode", smscode);
        map.put("username", user.getUsername());
        result.setResult(map);
        result.setSuccess(true);
        return result;
    }

    /**
     * 用户更改密码
     */
    @GetMapping("/passwordChange")
    public Result<SysUser> passwordChange(@RequestParam(name = "username") String username,
                                          @RequestParam(name = "password") String password,
                                          @RequestParam(name = "smscode") String smscode,
                                          @RequestParam(name = "phone") String phone) {
        Result<SysUser> result = new Result<SysUser>();
        if (oConvertUtils.isEmpty(username) || oConvertUtils.isEmpty(password) || oConvertUtils.isEmpty(smscode) || oConvertUtils.isEmpty(phone)) {
            result.setMessage("重置密码失败！");
            result.setSuccess(false);
            return result;
        }

        SysUser sysUser = new SysUser();
        Object object = redisUtil.get(phone);
        if (null == object) {
            result.setMessage("短信验证码失效！");
            result.setSuccess(false);
            return result;
        }
        if (!smscode.equals(object)) {
            result.setMessage("短信验证码不匹配！");
            result.setSuccess(false);
            return result;
        }
        sysUser = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username).eq(SysUser::getPhone, phone));
        if (sysUser == null) {
            result.setMessage("未找到用户！");
            result.setSuccess(false);
            return result;
        } else {
            sysUser.setPassword(new BCryptPasswordEncoder().encode(password));
            this.sysUserService.updateById(sysUser);
            result.setSuccess(true);
            result.setMessage("密码重置完成！");
            return result;
        }
    }

    /**
     * 获取所有有效用户
     */
    @GetMapping("/queryAllUser")
    public List<ComboModel> queryAllUser() {
        List<SysUser> sysUserList = sysUserService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getStatus, 1).eq(SysUser::getDelFlag, 0));
        if (CollUtil.isNotEmpty(sysUserList)) {
            List<ComboModel> comboModelList = sysUserList.stream().map(user -> {
                ComboModel model = new ComboModel();
                model.setTitle(user.getRealname());
                model.setId(user.getId());
                model.setUsername(user.getUsername());
                return model;
            }).collect(Collectors.toList());
            return comboModelList;
        }
        return new ArrayList<>();
    }

    /**
     * 根据用户姓名查询用户信息  模糊查询 realname || username
     *
     * @param name
     * @return
     */
    @GetMapping("/getUsersByName/{name}")
    public List<SysUser> getUsersByName(@PathVariable String name) {
        List<SysUser> sysUserList = sysUserService.list(new LambdaQueryWrapper<SysUser>().like(SysUser::getUsername, name).or().like(SysUser::getRealname, name));
        return sysUserList;
    }


    /**
     * 根据TOKEN获取用户的部分信息（返回的数据是可供表单设计器使用的数据）
     *
     * @return
     */
    @GetMapping("/getUserSectionInfoByToken")
    public Result<?> getUserSectionInfoByToken(HttpServletRequest request, @RequestParam(name = "token", required = false) String token) {
        try {
            LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            log.info(" ------ 通过令牌获取部分用户信息，当前用户： " + username);

            // 根据用户名查询用户信息
            SysUser sysUser = sysUserService.getUserByName(username);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("sysUserId", sysUser.getId());
            map.put("sysUserCode", sysUser.getUsername()); // 当前登录用户登录账号
            map.put("sysUserName", sysUser.getRealname()); // 当前登录用户真实名称
            map.put("sysOrgCode", sysUser.getOrgCode()); // 当前登录用户部门编号

            log.info(" ------ 通过令牌获取部分用户信息，已获取的用户信息： " + map);

            return Result.ok(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(500, "查询失败:" + e.getMessage());
        }
    }

    /**
     * 【APP端接口】获取用户列表  根据用户名和真实名 模糊匹配
     *
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/appUserList")
    public Result<?> appUserList(@RequestParam(name = "keyword", required = false) String keyword,
                                 @RequestParam(name = "username", required = false) String username,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 @RequestParam(name = "syncFlow", required = false) String syncFlow) {
        try {
            //TODO 从查询效率上将不要用mp的封装的page分页查询 建议自己写分页语句
            LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<SysUser>();
            if (oConvertUtils.isNotEmpty(syncFlow)) {
                query.eq(SysUser::getActivitiSync, "1");
            }
            query.eq(SysUser::getDelFlag, "0");
            if (oConvertUtils.isNotEmpty(username)) {
                if (username.contains(",")) {
                    query.in(SysUser::getUsername, username.split(","));
                } else {
                    query.eq(SysUser::getUsername, username);
                }
            } else {
                query.and(i -> i.like(SysUser::getUsername, keyword).or().like(SysUser::getRealname, keyword));
            }
            Page<SysUser> page = new Page<>(pageNo, pageSize);
            IPage<SysUser> res = this.sysUserService.page(page, query);
            return Result.ok(res);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(500, "查询失败:" + e.getMessage());
        }

    }

    /**
     * 获取被逻辑删除的用户列表，无分页
     *
     * @return logicDeletedUserList
     */
    @GetMapping("/recycleBin")
    public Result getRecycleBin() {
        List<SysUser> logicDeletedUserList = sysUserService.queryLogicDeleted();
        if (logicDeletedUserList.size() > 0) {
            // 批量查询用户的所属部门
            // step.1 先拿到全部的 userIds
            List<String> userIds = logicDeletedUserList.stream().map(SysUser::getId).collect(Collectors.toList());
            // step.2 通过 userIds，一次性查询用户的所属部门名字
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            logicDeletedUserList.forEach(item -> item.setOrgCode(useDepNames.get(item.getId())));
        }
        return Result.ok(logicDeletedUserList);
    }

    /**
     * 还原被逻辑删除的用户
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/putRecycleBin", method = RequestMethod.PUT)
    public Result putRecycleBin(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String userIds = jsonObject.getString("userIds");
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (StringUtils.isNotBlank(userIds)) {
            SysUser updateUser = new SysUser();
            updateUser.setUpdateBy(loginUser.getUsername());
            updateUser.setUpdateTime(new Date());
            sysUserService.revertLogicDeleted(Arrays.asList(userIds.split(",")), updateUser);
        }
        return Result.ok("还原成功");
    }

    /**
     * 彻底删除用户
     *
     * @param userIds 被删除的用户ID，多个id用半角逗号分割
     * @return
     */
    @RequestMapping(value = "/deleteRecycleBin", method = RequestMethod.DELETE)
    public Result deleteRecycleBin(@RequestParam("userIds") String userIds) {
        if (StringUtils.isNotBlank(userIds)) {
            sysUserService.removeLogicDeleted(Arrays.asList(userIds.split(",")));
        }
        return Result.ok("删除成功");
    }


    /**
     * 修改用户信息
     *
     * @param updateUserModel
     * @return
     */
    @PostMapping(value = "/editInfo")
    @ApiOperation(value = "修改用户信息")
    public Result<SysUser> editInfo(@RequestBody UpdateUserModel updateUserModel) {
        Result<SysUser> result = new Result<SysUser>();
        try {
            LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            SysUser sysUser = sysUserService.getUserByName(username);
            sysBaseAPI.addLog("编辑用户，id： " + user.getId(), CommonConstant.LOG_TYPE_2, 2);
            if (sysUser == null) {
                result.error500("未找到对应用户!");
            } else {
                if (updateUserModel.getRealname() != null)
                    sysUser.setRealname(updateUserModel.getRealname());
                if (updateUserModel.getAvatar() != null)
                    sysUser.setAvatar(updateUserModel.getAvatar());
                if (updateUserModel.getSex() != null)
                    sysUser.setSex(updateUserModel.getSex());
                if (updateUserModel.getBirthday() != null)
                    sysUser.setBirthday(updateUserModel.getBirthday());
                if (updateUserModel.getPhone() != null)
                    sysUser.setPhone(updateUserModel.getPhone());
                if (updateUserModel.getEmail() != null)
                    sysUser.setEmail(updateUserModel.getEmail());
                sysUser.setUpdateTime(new Date());
                sysUserService.updateById(sysUser);
                sysUserService.valiUserCahce(sysUser.getUsername());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败!");
        }
        return result;
    }

    /**
     * 根据userid获取用户信息和部门员工信息
     *
     * @return Result
     */
    @GetMapping("/queryChildrenByUsername")
    public Result queryChildrenByUsername(@RequestParam("userId") String userId) {
        //获取用户信息
        Map<String, Object> map = new HashMap<String, Object>();
        SysUser sysUser = sysUserService.getById(userId);
        String username = sysUser.getUsername();
        Integer identity = sysUser.getUserIdentity();
        map.put("sysUser", sysUser);
        if (identity != null && identity == 2) {
            //获取部门用户信息
            String departIds = sysUser.getDepartIds();
            if (StringUtils.isNotBlank(departIds)) {
                List<String> departIdList = Arrays.asList(departIds.split(","));
                List<SysUser> childrenUser = sysUserService.queryByDepIds(departIdList, username);
                map.put("children", childrenUser);
            }
        }
        return Result.ok(map);
    }

    /**
     * 移动端查询部门用户信息
     *
     * @param departId
     * @return
     */
    @GetMapping("/appQueryByDepartId")
    public Result<List<SysUser>> appQueryByDepartId(@RequestParam(name = "departId", required = false) String departId) {
        Result<List<SysUser>> result = new Result<List<SysUser>>();
        List<String> list = new ArrayList<String>();
        list.add(departId);
        List<SysUser> childrenUser = sysUserService.queryByDepIds(list, null);
        result.setResult(childrenUser);
        return result;
    }

    /**
     * 移动端查询用户信息(通过用户名模糊查询)
     *
     * @param keyword
     * @return
     */
    @GetMapping("/appQueryUser")
    public Result<List<SysUser>> appQueryUser(@RequestParam(name = "keyword", required = false) String keyword) {
        Result<List<SysUser>> result = new Result<List<SysUser>>();
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>();
        //TODO 外部模拟登陆临时账号，列表不显示
        queryWrapper.ne(SysUser::getUsername, "_reserve_user_external");
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(i -> i.like(SysUser::getUsername, keyword).or().like(SysUser::getRealname, keyword));
        }
        List<SysUser> list = sysUserService.list(queryWrapper);
        //批量查询用户的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询用户的所属部门名字
        List<String> userIds = list.stream().map(SysUser::getId).collect(Collectors.toList());
        if (userIds != null && userIds.size() > 0) {
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            list.forEach(item -> {
                item.setOrgCodeTxt(useDepNames.get(item.getId()));
            });
        }
        result.setResult(list);
        return result;
    }

    @GetMapping("getUserByName")
    public SysUser getUserByName(String userName) {
        SysUser sysUser = sysUserService.getUserByName(userName);
        if (sysUser != null)
            sysUser.setPassword(null);
        return sysUser;
    }

    @GetMapping("selectAllList")
    public List<SysUser> selectAllList() {
        return sysUserService.list(Wrappers.lambdaQuery(SysUser.class).
                select(SysUser::getId, SysUser::getUsername, SysUser::getRealname).eq(SysUser::getStatus, 1).eq(SysUser::getDelFlag, 0));
    }


    @GetMapping("getUserAll")
    public List<SysUser> getUserAll(@RequestParam(value = "userNameList", required = false) List<String> userNameList) {
        LambdaQueryWrapper<SysUser> queryWrapper = Wrappers.lambdaQuery(SysUser.class).select(SysUser::getId, SysUser::getUsername, SysUser::getRealname).eq(SysUser::getStatus, 1).eq(SysUser::getDelFlag, 0);
        if (CollUtil.isNotEmpty(userNameList)) {
            queryWrapper.in(SysUser::getUsername, userNameList);
        }
        return sysUserService.list(queryWrapper);
    }

    @GetMapping("getUsersAndDepartId")
    public Result<SysUser> getUsersAndDepartId(String userId) {
        // 当userId为空时查询所有用户，否则根据id查询用户信息
        SysUser sysUser = sysUserService.getById(userId);
        List<String> departIds = sysUserDepartService.listObjs(new LambdaQueryWrapper<SysUserDepart>()
                .select(SysUserDepart::getDepId).eq(SysUserDepart::getUserId, userId), Object::toString);
        sysUser.setDepartment(departIds);
        SysRole role = sysUserRoleService.getRoleByUserIdAndRoleCode(userId, "admin");
        sysUser.setIsAdmin(role != null);
        return Result.ok(sysUser);
    }

    /**
     * 根据账户和昵称模糊搜索用户
     *
     * @param usernameOrNickname
     * @return
     */
    @RequestMapping(value = "/queryUserLikeUsernameOrNickname", method = RequestMethod.GET)
    public Result<List<SysUser>> queryUserLikeUsernameOrNickname(@RequestParam(name = "usernameOrNickname", required = true) String usernameOrNickname) {
        List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<SysUser>().select(SysUser::getRealname, SysUser::getUsername).eq(SysUser::getDelFlag, 0).and(wrapper -> wrapper.like(SysUser::getUsername, usernameOrNickname).or().like(SysUser::getRealname, usernameOrNickname)));
        if (CollUtil.isNotEmpty(list)) {
            return Result.ok(list);
        }
        return Result.ok(new ArrayList<>());
    }

    /**
     * 根据username批量查询
     *
     * @param usernames
     * @return
     */
    @RequestMapping(value = "/queryUserByUsernames", method = RequestMethod.POST)
    public Result<List<SysUser>> queryUserByUsernames(@RequestBody List<String> usernames) {
        List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<SysUser>().select(SysUser::getRealname, SysUser::getUsername).in(SysUser::getUsername, usernames).eq(SysUser::getDelFlag, 0));
        if (CollUtil.isNotEmpty(list)) {
            return Result.ok(list);
        }
        return Result.ok(new ArrayList<>());
    }


    /**
     * 根据角色编码查询用户
     *
     * @param roleCode
     * @return
     */
    @RequestMapping(value = "/queryUserByRoleCode", method = RequestMethod.GET)
    public Result<List<SysUser>> queryUserByRoleCode(@RequestParam(name = "roleCode", required = true) String roleCode) {
        List<SysUser> list = sysUserService.queryUserByRoleCode(roleCode);
        if (CollUtil.isNotEmpty(list)) {
            return Result.ok(list);
        }
        return Result.ok(new ArrayList<>());
    }

    /**
     * 根据username查询当前username的领导
     *
     * @param username
     * @return
     */
    @RequestMapping(value = "/queryHisLeadershipByUsername", method = RequestMethod.GET)
    public Result<List<SysUser>> queryHisLeadershipByUsername(@RequestParam(name = "username", required = true) String username) {
        List<SysDepart> sysDeparts = sysDepartService.queryDepartsByUsername(username);
        if (CollUtil.isNotEmpty(sysDeparts)) {
            Set<String> leaderUsernames = sysDeparts.stream().filter(item -> item.getDepartLeader() != null).map(SysDepart::getDepartLeader).collect(Collectors.toSet());
            if (!leaderUsernames.isEmpty()) {
                List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<SysUser>().select(SysUser::getRealname, SysUser::getUsername).in(SysUser::getUsername, leaderUsernames));
                return Result.ok(list);
            }
        }
        return Result.ok(new ArrayList<>());
    }

    @PostMapping("checkPassword/{password}")
    @ApiOperation(value = "校验当前用户的密码是否正确")
    public Result<?> checkPassword(@PathVariable("password") String password) {
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String encoderPassword = sysUserService.getObj(new LambdaQueryWrapper<SysUser>().select(SysUser::getPassword)
                .eq(SysUser::getId, user.getId()), Object::toString);
        if (StrUtil.isBlank(encoderPassword)) {
            return Result.error("用户不存在！");
        }
        return new BCryptPasswordEncoder().matches(password, encoderPassword) ? Result.ok() : Result.error("密码验证失败！");
    }

}
